package handler

import (
	"sept15-test/model"
	"strconv"

	"github.com/gin-gonic/gin"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	des := c.PostForm("des")
	img := c.PostForm("img")

	if name == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品名称不可为空",
		})
		return
	}

	if des == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "商品详情不可为空",
		})
		return
	}

	shop := model.Shop{
		Name: name,
		Des:  des,
		Img:  img,
	}
	err := model.DB.Create(&shop).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var shop []*model.Shop
	model.DB.Offset(offset).Limit(size).Find(&shop)

	var total int64
	model.DB.Model(&shop).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "列表获取成功",
		"data":  shop,
		"total": total,
	})
	return
}

func Select(c *gin.Context) {
	id := c.Query("id")

	var shop model.Shop
	err := model.DB.Where("id=?", id).Find(&shop).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "搜索失败",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "搜索成功",
		"shop": shop,
	})
	return
}
